<?php
namespace Home\Controller;
use Think\Controller;

class Oauth2Controller extends Controller {

    //  定义连接腾讯qq的APPID和appkey
//    public $appid = '101213078';
//    public $appkey = '8fe0a385601d46aabbb3e149967d72a7';
//    public $callbackURL = 'http://ibeginner.sinaapp.com/';  //Oauth2/get_oauth2_code
    
    public function get_oauth2_code() {
        
        $appid = '101213078';
        $appkey = '8fe0a385601d46aabbb3e149967d72a7';
        $callbackURL = 'http://ibeginner.sinaapp.com/oauth2/qq/oauth/qq_callback.php';  //Oauth2/get_oauth2_code
        
        
        $currentURL = $_GET['currentURL'];  // 得到点击登录时所在的页面URL
        
        if($_REQUEST['state'] == $_SESSION['state']) { //csrf
    
//            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
//                . "client_id=" . $appid. "&redirect_uri=" . urlencode($callbackURL)
//                . "&client_secret=" . $appkey. "&code=" . $_REQUEST["code"];
            
            $token_url = "https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&"
                . "client_id=" . $appid. "&client_secret=" . $appkey. "&code=" . $_REQUEST["code"];

            $response = file_get_contents($token_url);
            if (strpos($response, "callback") !== false) {
                $lpos = strpos($response, "(");
                $rpos = strrpos($response, ")");
                $response  = substr($response, $lpos + 1, $rpos - $lpos -1);
                $msg = json_decode($response);
                if (isset($msg->error)) {
                    echo "解析从TX回调时出错了……";
                    echo "<h3>error:</h3>" . $msg->error;
                    echo "<h3>msg  :</h3>" . $msg->error_description;
                    exit;
                }
            }

            $params = array();
            parse_str($response, $params);

            //debug
            //print_r($params);

            //set access token to session
//            $_SESSION["access_token"] = $params["access_token"];
            //  获取openid的URL
            $graph_url = "https://graph.qq.com/oauth2.0/me?access_token=".$params["access_token"];
            $str  = file_get_contents($graph_url);
            if (strpos($str, "callback") !== false) {
                $lpos = strpos($str, "(");
                $rpos = strrpos($str, ")");
                $str  = substr($str, $lpos + 1, $rpos - $lpos -1);
            }

            $user = json_decode($str);
            if (isset($user->error)) {
                echo "根据access_token获取用户信息时出错了……";
                echo "<h3>error:</h3>" . $user->error;
                echo "<h3>msg  :</h3>" . $user->error_description;
                exit;
            }

            //debug
            //echo("Hello " . $user->openid);

            //set openid to session
            //$_SESSION["openid"] = $user->openid;  // 得到openid
            $get_user_info = "https://graph.qq.com/user/get_user_info?"."access_token=".$params["access_token"]
                ."&oauth_consumer_key=".$appid."&openid=".$user->openid."&format=json";

            $info = file_get_contents($get_user_info);
            $arr = json_decode($info, true);  // 得到用户的信息
            var_dump($arr);
            //  得到用户的信息之后保存到session，在提交评论的时候再保存到数据库
            //  登录成之后重新跳转到登录时的页面
            //header("Location:$currentURL");

        } else {
            echo("The state does not match. You may be a victim of CSRF.");
        }
        
    }
    
    public function to_callback_from_TX() {
        
    }
    
    /**
     * 点击“qq登陆”首先进入此方法
     * @param {Type}  
     */ 
    function qq_login() {
        
        session_start();
        //$currentURL = $_GET['currentURL'];  //获取从页面传递过来的URL
        $_SESSION['currentPageURL'] = $_GET['currentPageURL'];
//        echo "====================".$_SESSION['currentPageURL'];
//        exit;
        $appid = '101213078';
        $appkey = '8fe0a385601d46aabbb3e149967d72a7';
        $callbackURL = 'http://ibeginner.sinaapp.com/oauth2/qq/oauth/qq_callback.php';  //Oauth2/get_oauth2_code
        
        //申请到的appid
        //$_SESSION["appid"]    = 101213078; 

        //申请到的appkey
        //$_SESSION["appkey"]   = "8fe0a385601d46aabbb3e149967d72a7"; 

        //QQ登录成功后跳转的地址,请确保地址真实可用，否则会导致登录失败。
        //$_SESSION["callback"] = $pageURL;  //"http://ibeginner.sinaapp.com/"; 

        //QQ授权api接口.按需调用
        //$_SESSION["scope"] = "get_user_info,add_share,list_album,add_album,upload_pic,add_topic,add_one_blog,add_weibo";
        //$_SESSION["scope"] = "get_user_info";

        //  得到一个随机的MD5加密字符串
        $_SESSION['state'] = md5(uniqid(rand(), TRUE)); //CSRF protection
        $login_url = "https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=" 
            . $appid . "&redirect_uri=" . urlencode($callbackURL)
            . "&state=" . $_SESSION['state']
            . "&scope=get_user_info";  //  把跳转过来的URL记录下来
        //echo "=====================".$login_url;
        //  跳转到指定的回调页面，在页面上可以获取code
        header("Location:$login_url");
    }
}
